import { loginAPI } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const getDefaultState = () => {
  return {
    token: getToken(), // vuex的state值,使用本地持久化的(刷新时,默认去本地取一个)
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token // vuex里state存一份
    setToken(token) // 再给本地存一份
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  // 删除token
  REMOVE_TOKEN (state) {
    state.token = ''
    removeToken()
  }
}

const actions = {
  // 登录逻辑-封装个
  async loginActions ({ commit }, data) {
    const res = await loginAPI(data)
    console.log(res)
    commit('SET_TOKEN', res.data)
    return res // 把结果返回到调用处
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
